<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Http\Controllers;


use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Logic\WXOrderLogic;
use App\Model\Vip\VipConfList;
use Illuminate\Support\Facades\DB;

class Vip extends Base
{

    public function index()
    {
        return $this->returnData(
            VipConfList::where('status',1)->get(['id','name','price','level','buy_number','give_number','activity_conf_type_open','activity_conf_type_login'])
        );
    }


    /**
     * 创建购买会员权益订单
     * @return string
     * @throws ApiException
     */
    public function createOrder()
    {
        $vip_conf_object = DB::table('t_vip_conf')->where('id',$this->param['good_id'])->first();
        if (empty($vip_conf_object)) {
            throw new ApiException('商品不存在');
        }

        $level = DB::table('t_vip_conf')->where('id',function ($query)  {
            $query->from('t_vip_info')->where('uid',$this->uid)->where('expire_time','>',date('Y-m-d H:i:s'))->select(['vip_conf_id']);
        })->where('level','>',$vip_conf_object->level)->value('level');
        if (!empty($level)) {
            throw new ApiException('不能降级购买会员,除非等本次会员有效期结束');
        }

        $order_id = WXOrderLogic::instance()->createOrderId();
        $wx_data = WXOrderLogic::instance()->createOrder(
            $order_id,
            floatval($vip_conf_object->price),
            $vip_conf_object->name,
            time()
        );
        //插入订单表数据
        Tool::createPayInfo($order_id,$vip_conf_object->price,$this->uid,1,2,$this->param['good_id']);
        return $this->returnData($wx_data);
    }

}